<template>
  <div>
    <el-dialog
      v-model="props.dialogVisible"
      title="站点"
      draggable
      :before-close="handleListClose"
      width="75%"
    >
      <searchBox @handleSearch="handleSearch" @handleReset="handleReset">
        <el-form
          :inline="true"
          :model="searchFrom.param"
          label-width="auto"
          ref="siteManageRef"
        >
          <el-form-item label="网站名称" prop="name">
            <el-input
              placeholder="请输入"
              v-model.trim="searchFrom.param.name"
            ></el-input>
          </el-form-item>
          <el-form-item label="域名" prop="domainName">
            <el-input
              placeholder="请输入"
              v-model.trim="searchFrom.param.domainName"
            ></el-input>
          </el-form-item>

          <el-form-item label="国家" prop="newCountryId">
            <el-tree-select
              v-model="searchFrom.param.newCountryId"
              placeholder="请选择"
              :data="sys_country"
              style="width: 185px"
              :props="defaultProps"
            />
          </el-form-item>
          <el-form-item label="货币" prop="currencyId">
            <el-select
              v-model="searchFrom.param.currencyId"
              placeholder="请选择"
              style="width: 185px"
            >
              <el-option
                v-for="dict in sys_currency_code"
                :key="dict.id"
                :label="dict.label"
                :value="dict.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="语言" prop="languageId">
            <el-select
              v-model="searchFrom.param.languageId"
              placeholder="请选择"
              style="width: 185px"
            >
              <el-option
                v-for="dict in sys_language_type"
                :key="dict.id"
                :label="dict.description"
                :value="dict.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="站点类型" prop="websiteTypeId">
            <el-select
              v-model="searchFrom.param.websiteTypeId"
              placeholder="请选择"
              style="width: 185px"
            >
              <el-option
                v-for="dict in sys_site_type"
                :key="dict.id"
                :label="dict.name"
                :value="dict.id"
                :disabled="!dict.status"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </searchBox>
      <el-table
        :data="tableData"
        height="500px"
        :row-key="getRowKey"
        ref="siteSelectRef"
        @selection-change="handleSelectionChange"
      >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column prop="id" label="ID" width="100" />
      <el-table-column prop="code" label="网站编号" width="200" />
      <el-table-column prop="name" label="网站名称" />
      <el-table-column prop="port" label="端口" width="100" align="center" />
      <el-table-column prop="domainName" label="域名" width="200" />
      <el-table-column label="国家" prop="countryName" width="100" />
      <el-table-column label="支持货币" width="200">
        <template #default="scope">
          <el-space spacer=" " wrap>
            <el-tag size="small" v-for="(item, index) in scope.row.newCurrencyCodes" :key="index"
              :type="index === 0 ? 'primary' : 'info'">{{ item }}</el-tag>
          </el-space>
        </template>
      </el-table-column>

      <el-table-column label="支持语言" width="200">
        <template #default="scope">
          <el-space spacer=" " wrap>
            <el-tag size="small" v-for="(item, index) in scope.row.newLanguageNames" :key="index"
              :type="index === 0 ? 'primary' : 'info'">{{ item }}</el-tag>
          </el-space>
        </template>
      </el-table-column>

      <el-table-column prop="websiteTypeName" label="站点类型" align="center" />
      <el-table-column label="当前状态" align="center" width="100">
        <template #default="scope">
          <el-switch v-model="scope.row.status" :active-value="1" :inactive-value="0" active-text="开启"
            inactive-text="关闭" inline-prompt @change="switchProcess(scope.row)" />
        </template>
      </el-table-column>
      <el-table-column prop="newLastModified" label="更新时间" align="center" width="200" />
      <el-table-column prop="newPublishStatus" label="发布状态" align="center" width="200">
        <template #default="scope">
          <el-text class="mx-1" :type="scope.row.newPublishStatus?.elTagClass">{{ scope.row.newPublishStatus?.label
          }}</el-text>
        </template>
      </el-table-column>
      </el-table>
      <Pagination
        :total="total"
        :limit="searchFrom.pageSize"
        :page="searchFrom.pageNum"
        @pagination="handleCurrentChange"
      ></Pagination>

      <template #footer>
        <div class="dialog-footer" v-if="!props.newType">
          <el-button @click="handleListClose">取消</el-button>
          <el-button type="primary" @click="handleListSure"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
  <script setup>
import { ref, defineProps, defineEmits, onMounted, watch } from "vue";
import "@/api/login/index.js";
import "@/api/new_system/index.js";
import "@/api/new_product/index.js";
import "@/api/rate/index.js";
import "@/api/order/index.js";
import "@/api/site/index.js";

const { proxy } = getCurrentInstance();
const emits = defineEmits(["handleListClose", "handleListSure"]);
const { sys_publish_status } = proxy.useDict("sys_publish_status");
const total = ref(0);
const sys_language_type = ref([]); //语言
const sys_currency_code = ref([]); //货币
const sys_country = ref([]); //国家
const sys_site_type = ref([]); //站点类型
const tableData = ref([]);
const selectedRows = ref([]);
const props = defineProps({
  // 判断类型：true：查看列表，false是选择类型
  newType: {
    type: Boolean,
    default: true,
  },
  // 显示隐藏
  dialogVisible: {
    type: Boolean,
    default: false,
  },
  // 传值数据对象
  listItem: {
    type: Object,
    default: {},
  },
});
const searchFrom = ref({
  pageNum: 1,
  pageSize: 10,
  param: {
    websiteTypeId: null, //站点类别（站点类型）
    name: "", //网站名称
    domainName: "", //域名
    languageId: "", //语言id
    countryId: "", //区域id(国家)
    currencyId: "", //货币id
    status: 1, //状态
    publishStatus:['Succeed','Failed'],
    newCountryId:''
  },
});
const getRowKey = (row) => {
  return row.id;
};
// 勾选
const handleSelectionChange = (rows) => {
  if (rows) {
    selectedRows.value = rows.map((item) => item.id);
  } else {
    selectedRows.value = [];
  }
};
onMounted(() => {
  getSelectList();
});
const getList = () => {
  site.general
    .sitewebsiteList({
      data: searchFrom.value,
    })
    .then((res) => {
      total.value = res.total;
      if (res.data?.length) {
        res.data = res.data.map((code) => {
          return {
            ...code,
            newCurrencyCodes: publicSorting(code.currencyCode, code.currencyCodes),//支持货币
            newLanguageNames: publicSorting(code.languageName, code.languageNames),//支持货币
            newPublishStatus: sys_publish_status.value.find(
              (e) => e.value === code.publishStatus
            ),
            newLastModified: proxy.DateTime(code.lastModified),
          };
        });
      }
      tableData.value = res.data;
    });
};
const handleListClose = () => {
  selectedRows.value = [];
  proxy.$refs["siteSelectRef"].clearSelection();
  emits("handleListClose");
};
const handleListSure = () => {
  if (!selectedRows.value.length) return proxy.$modal.msgError("请勾选数据");
  emits("handleListSure", selectedRows.value);
  selectedRows.value = [];
  proxy.$refs["siteSelectRef"].clearSelection();
};
const getSelectList = () => {
  let from = {
    pageNum: 1,
    pageSize: 999,
    param: {},
  };
  // 语言

  product.language.languageList().then((res) => {
    sys_language_type.value = res.data;
  });
  // 获取货币
  product.currency.currencyList().then((res) => {
    if (res.data?.length) {
      res.data = res.data.map((code) => {
        return {
          ...code,
          label: code.description,
        };
      });
    }
    sys_currency_code.value = res.data;
  });
  // 站点类型
  site.general
    .sitewebsitetypeList({
      data: from,
    })
    .then((res) => {
      sys_site_type.value = res.data;
    });

  getCountry(from);
};
const getCountry = async (from) => {
  site.country
    .countryList({
      data: from,
    })
    .then((res) => {
      res.data = addLevelToTree(res.data);
      sys_country.value = res.data;
    });
};
const addLevelToTree= (tree, parentLevel = 0) => {
  return tree.map((item) => ({
    ...item,
    newId: `${item.id}-${parentLevel+1}`,
    children: item.children
    ? addLevelToTree(item.children, parentLevel + 1)
    : undefined,
  })
  )
}
// 搜索
const handleSearch = () => {
  console.log(searchFrom.value.param.newCountryId);
  let newCountry= searchFrom.value.param.newCountryId
  const newMatch=newCountry.match(/([-+]\d*\.?\d+)/);
  searchFrom.value.param.countryId=newCountry.slice(0, newMatch.index);
  getList();
};
// 重置
const handleReset = () => {
  proxy.resetForm("siteManageRef");
  getList();
};
// 分页设置选项
const handleCurrentChange = (val) => {
  searchFrom.value.pageNum = val.page;
  searchFrom.value.pageSize = val.limit;
  getList();
};

watch(
  () => props.dialogVisible,
  () => {
    if (!props.dialogVisible) return;
    if (props.newType) {
      searchFrom.value.param.ids = props.listItem.websiteIds;
    } else {
      searchFrom.value.param.ids = null;
      getSetTimeout();
    }
    getList();
  }
);
const getWebsiteIds = () => {
  // console.log(props.listItem.websiteIds,'走到这一步');
  if (props.listItem.websiteIds) {
    props.listItem.websiteIds.forEach((e) => {
      const existingRow = tableData.value.find((item) => item.id === e);
      if (existingRow) {
        proxy.$refs["siteSelectRef"].toggleRowSelection(existingRow, true);
      }
    });
  }
};
var defaultProps = reactive({
  children: "children",
  label: "description",
  value: "newId", // 指定 id 作为 value 属性
});
let intervalId = null;
const getSetTimeout = () => {
  if (intervalId) return; // 如果已经有一个轮询在进行中，则不再启动新的轮询
  intervalId = setInterval(() => {
    if (tableData.value.length) {
      clearInterval(intervalId);
      intervalId = null;
      getWebsiteIds();
    } else {
      getWebsiteIds();
    }
  }, 1000);
};
const publicSorting = (code, List) => {
  return List.sort((a, b) => (a === code ? -1 : b === code ? 1 : 0));
}
</script>
  <style>
.dialog-footer {
  padding: 20px 0 10px 0;
}
</style>